import React, { useState, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import { Card, Table, Form, Input, Button, DatePicker, Select, Space, Tag, Modal, message, Descriptions, InputNumber } from 'antd';
import { SearchOutlined, ReloadOutlined, EyeOutlined, CheckOutlined } from '@ant-design/icons';
import { request } from 'umi';
import moment from 'moment';

const { RangePicker } = DatePicker;
const { Option } = Select;

// 获取核销记录列表
const fetchVerifyRecords = async (params) => {
  return request('/api/v1/groupbuy/verify', {
    method: 'GET',
    params,
  });
};

// 获取核销详情
const fetchVerifyDetail = async (id) => {
  return request(`/api/v1/groupbuy/verify/${id}`, {
    method: 'GET',
  });
};

// 获取门店列表
const fetchStores = async () => {
  try {
    const res = await request('/api/v1/store', {
      method: 'GET',
    });
    if (res.success) {
      setStores(res.data || []);
    }
  } catch (error) {
    console.error('获取门店列表出错:', error);
  }
};

const GroupBuyVerify = () => {
  const [records, setRecords] = useState([]);
  const [loading, setLoading] = useState(false);
  const [form] = Form.useForm();
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
  });
  const [searchParams, setSearchParams] = useState({});
  const [detailVisible, setDetailVisible] = useState(false);
  const [currentRecord, setCurrentRecord] = useState(null);
  const [verifyVisible, setVerifyVisible] = useState(false);
  const [verifyForm] = Form.useForm();
  const [submitLoading, setSubmitLoading] = useState(false);
  const [stores, setStores] = useState([]);

  // 获取核销记录列表
  const fetchRecordList = async () => {
    try {
      setLoading(true);
      const res = await fetchVerifyRecords({
        page: pagination.current,
        pageSize: pagination.pageSize,
        ...searchParams,
      });
      if (res.success) {
        setRecords(res.data.list || []);
      } else {
        message.error(res.message || '获取核销记录失败');
      }
    } catch (error) {
      console.error('获取核销记录出错:', error);
      message.error('获取核销记录失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchRecordList();
  }, [pagination.current, pagination.pageSize, searchParams]);

  useEffect(() => {
    fetchStores();
  }, []);

  // 查看核销详情
  const handleViewDetail = async (record) => {
    try {
      setLoading(true);
      const res = await fetchVerifyDetail(record.id);
      if (res.success) {
        setCurrentRecord(res.data);
        setDetailVisible(true);
      } else {
        message.error(res.message || '获取核销详情失败');
      }
    } catch (error) {
      console.error('获取核销详情出错:', error);
      message.error('获取核销详情失败');
    } finally {
      setLoading(false);
    }
  };

  // 添加核销功能
  const handleVerify = () => {
    setVerifyVisible(true);
  };

  // 表格列定义
  const columns = [
    {
      title: '活动名称',
      dataIndex: 'activity_name',
      key: 'activity_name',
      width: 180,
    },
    {
      
    },
    {
      
    },
    {
      title: '用户',
      dataIndex: 'username',
      key: 'username',
      width: 120,
    },
    {
      title: '订单号',
      dataIndex: 'orderNo',
      key: 'orderNo',
      width: 180,
    },
    {
      title: '核销时间',
      dataIndex: 'verifyTime',
      key: 'verifyTime',
      width: 180,
    },
    {
      title: '核销门店',
      dataIndex: 'storeName',
      key: 'storeName',
      width: 150,
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space>
          <Button 
            type="link" 
            icon={<EyeOutlined />} 
            onClick={() => handleViewDetail(record)}
          >
            详情
          </Button>
          <Button 
            type="link" 
            icon={<CheckOutlined />} 
            onClick={() => handleVerify(record)}
          >
            核销
          </Button>
        </Space>
      ),
    },
  ];

  // 处理搜索
  const handleSearch = (values) => {
    const params = {};
    if (values.activity_name) {
      params.activity_name = values.activity_name;
    }
    if (values.username) {
      params.username = values.username;
    }
    if (values.orderNo) {
      params.orderNo = values.orderNo;
    }
    if (values.dateRange && values.dateRange.length === 2) {
      params.startTime = values.dateRange[0].format('YYYY-MM-DD HH:mm:ss');
      params.endTime = values.dateRange[1].format('YYYY-MM-DD HH:mm:ss');
    }
    
    setSearchParams(params);
    setPagination({
      ...pagination,
      current: 1, // 重置到第一页
    });
  };

  // 重置搜索
  const handleReset = () => {
    form.resetFields();
    setSearchParams({});
    setPagination({
      ...pagination,
      current: 1,
    });
  };

  // 处理表格变化
  const handleTableChange = (pagination, filters, sorter) => {
    setPagination(pagination);
  };

  // 添加核销表单弹窗
  const handleVerifySubmit = async (values) => {
    try {
      setSubmitLoading(true);
      
      // 如果没有订单ID，生成一个临时ID
      if (!values.orderId) {
        values.orderId = Date.now(); // 使用时间戳作为临时订单ID
      }
      
      const res = await request('/api/v1/groupbuy/verify', {
        method: 'POST',
        data: values,
      });
      if (res.success) {
        message.success('核销成功');
        fetchRecordList();
        verifyForm.resetFields();
        setVerifyVisible(false);
      } else {
        message.error(res.message || '核销失败');
      }
    } catch (error) {
      console.error('核销出错:', error);
      message.error('核销失败');
    } finally {
      setSubmitLoading(false);
    }
  };

  return (
    <PageContainer>
      <Card>
        <Form
          form={form}
          layout="inline"
          onFinish={handleSearch}
          style={{ marginBottom: 24 }}
        >
          <Form.Item name="activity_name" label="活动名称">
            <Input placeholder="请输入活动名称" allowClear />
          </Form.Item>
          <Form.Item name="username" label="用户名">
            <Input placeholder="请输入用户名" allowClear />
          </Form.Item>
          <Form.Item name="orderNo" label="订单号">
            <Input placeholder="请输入订单号" allowClear />
          </Form.Item>
          <Form.Item name="dateRange" label="核销时间">
            <RangePicker
              showTime
              format="YYYY-MM-DD HH:mm:ss"
              placeholder={['开始时间', '结束时间']}
            />
          </Form.Item>
          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>
                搜索
              </Button>
              <Button icon={<ReloadOutlined />} onClick={handleReset}>
                重置
              </Button>
            </Space>
          </Form.Item>
        </Form>

        <Table
          columns={columns}
          dataSource={records}
          rowKey="id"
          loading={loading}
          pagination={pagination}
          onChange={handleTableChange}
          scroll={{ x: 1100 }}
        />

        {/* 核销详情弹窗 */}
        <Modal
          title="核销详情"
          visible={detailVisible}
          onCancel={() => setDetailVisible(false)}
          footer={[
            <Button key="close" onClick={() => setDetailVisible(false)}>
              关闭
            </Button>,
          ]}
          width={700}
        >
          {currentRecord && (
            <Descriptions bordered column={2}>
              <Descriptions.Item label="活动名称">{currentRecord.activity_name}</Descriptions.Item>
              <Descriptions.Item label="用户名">{currentRecord.username}</Descriptions.Item>
              <Descriptions.Item label="订单号">{currentRecord.orderNo}</Descriptions.Item>
              <Descriptions.Item label="订单金额">¥{(currentRecord.orderAmount / 100).toFixed(2)}</Descriptions.Item>
              <Descriptions.Item label="核销时间">{currentRecord.verifyTime}</Descriptions.Item>
              <Descriptions.Item label="核销门店">{currentRecord.storeName}</Descriptions.Item>
              <Descriptions.Item label="操作员">{currentRecord.operatorName}</Descriptions.Item>
              
              <Descriptions.Item label="备注" span={2}>{currentRecord.remark || '-'}</Descriptions.Item>
            </Descriptions>
          )}
        </Modal>

        {/* 添加核销表单弹窗 */}
        <Modal
          title="核销团购券"
          visible={verifyVisible}
          onCancel={() => setVerifyVisible(false)}
          footer={null}
        >
          <Form
            form={verifyForm}
            layout="vertical"
            onFinish={handleVerifySubmit}
          >
            <Form.Item
              name="group_buy_order_id"
              label="团购订单ID"
              rules={[{ required: true, message: '请输入团购订单ID' }]}
            >
              <Input placeholder="请输入团购订单ID" />
            </Form.Item>
            <Form.Item
              name="orderNo"
              label="订单号"
              rules={[{ required: true, message: '请输入订单号' }]}
            >
              <Input placeholder="请输入订单号" />
            </Form.Item>
            
            <Form.Item
              name="storeId"
              label="核销门店"
              rules={[{ required: true, message: '请选择核销门店' }]}
            >
              <Select placeholder="请选择核销门店">
                {stores.map(store => (
                  <Option key={store.id} value={store.id}>{store.name}</Option>
                ))}
              </Select>
            </Form.Item>
            <Form.Item name="remark" label="备注">
              <Input.TextArea rows={4} placeholder="请输入备注信息" />
            </Form.Item>
            <Form.Item>
              <Button type="primary" htmlType="submit" loading={submitLoading} block>
                确认核销
              </Button>
            </Form.Item>
          </Form>
        </Modal>
      </Card>
    </PageContainer>
  );
};

export default GroupBuyVerify;